package com.hunt.app.task;

import com.hunt.service.app.CrawlingPopularityStockService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * 定时爬取同花顺最欢迎个股
 */
@Component
public class CrawlingPopularityStockTask {

    private static final Logger log = LoggerFactory.getLogger(CrawlingPopularityStockTask.class);

    private static final String CRAWLING_POPULARITY_STOCK_KEY = "CRAWLING_POPULARITY_STOCK_KEY";

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    @Autowired
    private CrawlingPopularityStockService crawlingPopularityStockService;


//    @Scheduled(cron = "0 0/5 * * * ? ")
    //@Scheduled(cron = "0 0/30 * * * ? ")
    public void crawlingStarter(){
        //集群部署情况做分布式锁抢占式 返回true抢到了锁  返回false没抢到直接return
        Boolean b = redisTemplate.opsForValue().setIfAbsent(CRAWLING_POPULARITY_STOCK_KEY, "The_timer_is_Executing");
        if (b){
            log.info("爬取同花顺热门股票定时器启动");
            try {
                crawlingPopularityStockService.crawlingAndInsert();
                Thread.sleep(5000);
            }catch (InterruptedException e){
                redisTemplate.delete(CRAWLING_POPULARITY_STOCK_KEY);
                log.info("获取同花顺热门股票定时器执行失败,并已经释放执行锁");
                e.printStackTrace();
            }
            //执行完毕释放锁
            redisTemplate.delete(CRAWLING_POPULARITY_STOCK_KEY);
            log.info("获取同花顺热门股票定时器执行成功,并已经释放执行锁");
        }
    }
}
